#!/usr/bin/env python
# -*- coding: utf-8 -*-

import json
import os, sys

from Atm.core import db_handler

def load_current_balance(account_id):
    '''
    加载用户余额
    :param account_id: 用户id
    :return: 用户数据
    '''
    db_api = db_handler.db_handler()
    account_file = os.path.join(db_api, '%s.json' % account_id)
    if os.path.isfile(account_file):
        with open(account_file, 'r', encoding='utf-8') as f:
            account_data = json.load(f)
            return account_data

def dump_account(account_data):
    '''
    更新用户信息
    :param account_data:
    :return: True
    '''
    db_api = db_handler.db_handler()
    account_file = os.path.join(db_api, '%s.json' % account_data['id'])
    with open(account_file, 'w', encoding='utf-8') as f:
        json.dump(account_data, f)
        return True

def load_bill(account_id):
    '''
    加载用户账单信息
    :param account_id: 用户id
    :return:   返回包含用户账单的列表
    '''
    account_list = []
    db_api = db_handler.bill_db_handler()
    account_file = os.path.join(db_api, '%s.log' % account_id)
    if os.path.isfile(account_file):
        with open(account_file, 'r', encoding='utf-8') as f:
            for item in f:
                account_list.append(item.strip())
        return account_list

def dump_bill(account_bill):
    '''
    更新用户账单
    :param account_bill:
    :return:
    '''
    db_api = db_handler.bill_db_handler()
    account_file = os.path.join(db_api, '%s.log' % account_bill['id'])
    with open(account_file, 'a', encoding='utf-8') as f:
        account_bill = json.dumps(account_bill)
        f.write(account_bill + '\n')